import os
import shutil


def copycompensatory(src, traget):
    dir = "C:\\Users\\jiufenshiren\\Downloads\\loan_file"
    target = "C:\\Users\\jiufenshiren\\Downloads\\loan_file_new"
    # 判断target目录是否存在
    if not os.path.exists(target):
        os.makedirs(target)
    readfolder(dir, target)


def readfolder(folder, target):
    listFolder = os.listdir(folder)
    for datedir in listFolder:
        fulldatedir = os.path.join(folder, datedir)
        # 判断是不是文件夹，是文件夹递归执行，不是文件夹进行判断，移动文件
        if os.path.isdir(fulldatedir):
            readfolder(fulldatedir, target)
        else:
            if fulldatedir.endswith('COMPENSATION'):
                newfulldatedir = os.path.join(target, datedir)
                if os.path.exists(newfulldatedir):
                    newfulldatedir = newfulldatedir + '1'
                    # 创建文件
                print(fulldatedir + ' -> ' + newfulldatedir)
                copyfile(fulldatedir, newfulldatedir)


def copyfile(src, target):
    shutil.copy2(src, target)


def readfile(newfolderdir, targetfile):
    listdir = os.listdir(newfolderdir)
    for datedir in listdir:
        fulldatedir = os.path.join(newfolderdir, datedir)
        with open(fulldatedir, 'r', encoding='utf-8') as f:
            # reader = csv.reader(f, delimiter=',')
            lines = f.readlines()
            # 读取 lines的行数
            print(f"{datedir} has {len(lines)} lines.")
            for i, line in enumerate(lines):
                if i == 0:
                    continue
                else:
                    line = line.strip()
                    if line:
                        with open(targetfile, 'a', encoding='utf-8') as targetf:
                            targetf.write(line + '\n')


if __name__ == '__main__':
    src = "C:\\Users\\jiufenshiren\\Downloads\\loan_file_new"
    tarfile = "C:\\Users\\jiufenshiren\\Downloads\\loan_file_new\\compensatory"
    readfile(src, tarfile)
